package com.csw.android.ffmpegtest.ui.section1

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.csw.android.ffmpegtest.R
import com.csw.android.ffmpegtest.databinding.LayoutSection102Binding
import com.csw.android.ffmpegtest.ui.base.DataBindingFragment

/**
 * 使用自定义View渲染一张图片
 */
class Section102 : DataBindingFragment<LayoutSection102Binding>() {

    override fun getContentViewID(): Int {
        return R.layout.layout_section_102
    }

    override fun initData() {
        super.initData()
        dataBinding?.content?.run {
            addView(
                PictureView(context).apply {
                    setPictureId(R.drawable.benxi)
                },
                ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
            )
        }
    }

    class PictureView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
    ) : View(context, attrs, defStyleAttr) {

        private var picture: Drawable? = null
            set(value) {
                field = value
                postInvalidate()
            }

        fun setPictureId(pictureId: Int) {
            picture = ContextCompat.getDrawable(context, pictureId)?.apply {
                setBounds(0, 0, intrinsicWidth, intrinsicHeight)
            }
        }

        override fun onDraw(canvas: Canvas) {
            super.onDraw(canvas)
            picture?.run {
                canvas.save()
                canvas.translate(width / 2f, height / 2f)
                canvas.translate(bounds.width() / -2f, bounds.height() / -2f)
                draw(canvas)
                canvas.restore()
            }
        }
    }
}

